import axios from 'axios';
import { getToken, removeToken, getRefreshToken, setToken, setRefreshToken } from '@/utils/auth';
import router from '@/router';
const request = axios.create({
    timeout: 100000,
    baseURL: '/api'
});

request.interceptors.request.use(
    (config) => {
        const token = getToken();
        if (token) {
            config.headers.Authorization = `Bearer ${token}`;
        }
        return config;
    },
    (error) => {
        console.log(error);
        return Promise.reject(error);
    }
);
request.interceptors.response.use(
    (response) => {
        return response.data;
    },
    (error) => {
        console.log(error);
        //如果响应的状态码是401的话,说明token不存在或者是无效的
        if (error.response && error.response.status == 401) {
            removeToken();//清除老的token
            if(!error.config.retry){//如果是这次已经是重试的操作了，还是返回401.那就不用再重试
                error.config.retry=true;
                return refreshToken(error.config);
            }else{
                router.push('/login');
                return Promise.reject(new Error('重试失败，请重新登录吧'));
            }
        }
        return Promise.reject(error);
    }
);
async function refreshToken(config) {
    //先获取刷新token
    const refreshToken = getRefreshToken();
    if (!refreshToken) {
        router.push('/login');
        return Promise.reject(new Error('刷新token不存在，无法刷新'));
    }
    try {
        //如果刷新 token存在的话，则调用刷新token的方法获取新的token
        const response = await axios.post(
            '/api/auth/refresh-token', {}, {
            headers: { Authorization: `Bearer ${refreshToken}` }
        }
        )
        const { token, refreshToken: newRefreshToken } = response.data?.data;
        if (token) {
            setToken(token);
            setRefreshToken(newRefreshToken);
            //刷新得到最新的token后可以重新发送原来失败的请求
            //把原来的请求认证token改变 刷新的事的最新的token
            config.headers.Authorization = `Bearer ${token}`;
            return request(config);
        }else{
            return Promise.reject(new Error('刷新token失败'))
        }
    } catch (error) {
        return Promise.reject(error)
    }
}
export default request;